import router from '@/routers';
import { loginRoutePath, STORAGE_TOKEN_KEY } from '@/types/meta';
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core';
import { ErrorResponse, onError } from '@apollo/client/link/error';
import { notification } from 'ant-design-vue';
const setTokenHeader = () => {
	const savedToken = localStorage.getItem(STORAGE_TOKEN_KEY);
	return { Authorization: `Bearer ${savedToken}` };
};

const errorLink = onError((error: ErrorResponse) => {
	const { graphQLErrors, networkError } = error;
	if (graphQLErrors) {
		notification.error({
			message: graphQLErrors[0].message,
			description: graphQLErrors[0].originalError?.message,
		});
		graphQLErrors.find((x) => x.message === 'Unauthorized') &&
			localStorage.removeItem(STORAGE_TOKEN_KEY);
		router.push({
			path: loginRoutePath,
			replace: true,
		});
	}
	if (networkError) {
		notification.error({
			message: networkError.name,
			description: networkError.message,
		});
	}
});
const httpLink = createHttpLink({
	headers: { ...setTokenHeader() },
});
const cache = new InMemoryCache();

const apolloClient = new ApolloClient({
	link: errorLink.concat(httpLink),
	cache,
});

export default apolloClient;
